package de.ret_world.openrpgstudio.engine.loading;

import com.artemis.World;
import de.ret_world.openrpgstudio.editor.gui.DatabaseDialog;
import de.ret_world.openrpgstudio.editor.helpers.ScriptTools;
import de.ret_world.openrpgstudio.engine.GameLauncher;
import org.apache.log4j.Logger;
import org.java.plugin.PluginLifecycleException;
import org.java.plugin.registry.Extension;
import org.java.plugin.registry.ExtensionPoint;
import org.jrabbit.base.data.thread.WatchableGLThread;

/**
 *
 * @author Emu
 */
public class InitializeScriptsThread extends WatchableGLThread {
    
    private World entityWorld;
    
    protected InitializeScriptsThread(World entityWorld) {
        this.entityWorld = entityWorld;
    }
    
    @Override
    protected void act() {
        Logger.getLogger(LoadingLoop.class).info("Running init scripts...");
        ScriptTools.getInstance().executeStartScript();
        
        Logger.getLogger(LoadingLoop.class).info("Running LoadPlugins...");
        ExtensionPoint toolExtPoint = GameLauncher.manager.getRegistry().getExtensionPoint(GameLauncher.PLUGIN_ID, "LoadPlugin");
        LoadPlugin plugin = null;
        for (Extension ext : toolExtPoint.getConnectedExtensions()) {
            //initialize the plugin
            if (GameLauncher.manager.isPluginEnabled(ext.getDeclaringPluginDescriptor())) {
                try {
                    // Activate plug-in that declares extension.
                    GameLauncher.manager.activatePlugin(ext.getDeclaringPluginDescriptor().getId());
                    // Get plug-in class loader.
                    ClassLoader classLoader = GameLauncher.manager.getPluginClassLoader(ext.getDeclaringPluginDescriptor());
                    // Load Tool class.
                    Class<?> clazz = classLoader.loadClass(ext.getParameter("class").valueAsString());
                    // Create Tool instance.
                    plugin = (LoadPlugin) clazz.newInstance();
                    // Initialize class instance according to interface contract.
                    plugin.setEntityWorld(entityWorld);
                    plugin.load();
                } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | PluginLifecycleException ex) {
                    Logger.getLogger(LoadingLoop.class).error(ex);
                }
            }
        }
        
        Logger.getLogger(LoadingLoop.class).info("...Done");
    }
}
